package com.example.music.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;

import com.example.music.Bean.LocalMusicBean;
import com.example.music.DB.PlayHistroyInfo;
import com.example.music.DB.SongInfo;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class MusicPlayer {
    private static MusicPlayer instance;
    private MediaPlayer mediaPlayer;
    private String currentSong;
    private boolean isPlaying;
    private OnPlaybackListener playbackListener;
    private Handler handler;
    private Set<LocalMusicBean> playbackHistory; // 播放记录列表

    Integer curUserId = -1;
    private MusicPlayer() {
        mediaPlayer = new MediaPlayer();
        isPlaying = false;
        handler = new Handler();
        //提取初始播放记录
        /**
         * 1.查询所有
         * 2.按id查询歌列表
         */
        Set<PlayHistroyInfo> playHistroySet = new LinkedHashSet<>(LitePal.select("UserId,SongId")
                .find(PlayHistroyInfo.class));
        Set<SongInfo> playHistroyList;
        for(PlayHistroyInfo item:playHistroySet) {
            playHistroyList = new LinkedHashSet<>(LitePal.select("Id")
                    .where("Id=?",item.getSongId()+"")
                    .find(SongInfo.class));
            Log.e("打印数据库的播放记录：",playHistroyList.toString());
        }

        playbackHistory = new LinkedHashSet<>();
    }

    public static synchronized MusicPlayer getInstance() {
        if (instance == null) {
            instance = new MusicPlayer();
        }
        return instance;
    }

    public void setPlaybackListener(OnPlaybackListener listener) {
        playbackListener = listener;
    }

    public void seekTo(int position) {
        if (isPlaying) {
            mediaPlayer.seekTo(position);
        }
    }

    public void play(String songPath) {
        try {
            if (!isPlaying) {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(songPath);
                mediaPlayer.prepare();
                mediaPlayer.start();
                currentSong = songPath;
                isPlaying = true;
                notifyPlaybackState(true);
                startUpdatingProgress();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void play(LocalMusicBean bean) {
        try {
            if (!isPlaying) {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(bean.getPath());
                mediaPlayer.prepare();
                mediaPlayer.start();
                currentSong = bean.getPath();
                isPlaying = true;
                notifyPlaybackState(true);
                startUpdatingProgress();
                addToPlaybackHistory(bean); // 将当前歌曲添加到播放记录列表
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void pause() {
        if (isPlaying) {
            mediaPlayer.pause();
            isPlaying = false;
            notifyPlaybackState(false);
            stopUpdatingProgress();
        }
    }

    public void resume() {
        if (!isPlaying && currentSong != null) {
            mediaPlayer.start();
            isPlaying = true;
            notifyPlaybackState(true);
            startUpdatingProgress();
        }
    }

    public void stop() {
        if (isPlaying) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            isPlaying = false;
            notifyPlaybackState(false);
            stopUpdatingProgress();
        }
    }

    public boolean isPlaying() {
        return isPlaying;
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    private void startUpdatingProgress() {
        handler.postDelayed(updateProgressTask, 1000);
    }

    private void stopUpdatingProgress() {
        handler.removeCallbacks(updateProgressTask);
    }

    private Runnable updateProgressTask = new Runnable() {
        @Override
        public void run() {
            if (isPlaying) {
                notifyProgressUpdate(mediaPlayer.getCurrentPosition(), mediaPlayer.getDuration());
                handler.postDelayed(this, 1000);
            }
        }
    };

    private void notifyPlaybackState(boolean isPlaying) {
        if (playbackListener != null) {
            playbackListener.onPlaybackStateChanged(isPlaying);
        }
    }

    private void notifyProgressUpdate(int currentPosition, int duration) {
        if (playbackListener != null) {
            playbackListener.onProgressUpdate(currentPosition, duration);
        }
    }

    //音乐类的播放记录
    public void addToPlaybackHistory(LocalMusicBean bean) {
        playbackHistory.add(bean);
    }

    public Set<LocalMusicBean> getPlaybackHistory() {
        return playbackHistory;
    }

    public void clearPlaybackHistory() {
        playbackHistory.clear();
    }

    public interface OnPlaybackListener {
        void onPlaybackStateChanged(boolean isPlaying);
        void onProgressUpdate(int currentPosition, int duration);
    }
}